package com.study.Service.Impl;

import com.common.Utils.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.study.Entity.Article;
import com.study.Mapper.ArticleMapper;
import com.study.Service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public PageInfo<Article> getArticleList(Integer pageNum, Integer pageSize, String categoryId, String title,String status) {
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleMapper.getArticleList(categoryId,title,status);
        return new PageInfo<>(articleList);
    }

    @Override
    public void addArticle(Article article) {
        String token=article.getToken();
        String username = JwtUtil.extractUsername(token);
        article.setCreateUser(username);
        article.setArticleId(makeId());
        article.setAuthorName(username);
        article.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        articleMapper.addArticle(article);
    }


    @Override
    public void updateArticle(Article article) {
        String token=article.getToken();
        String username = JwtUtil.extractUsername(token);
        article.setUpdateUser(username);
        article.setUpdateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        articleMapper.updateArticle(article);
    }

    @Override
    public void deleteArticle(String articleId) {
        articleMapper.deleteArticle(articleId);
        articleMapper.deleteSection(articleId);
    }

    @Override
    public PageInfo<Article> getArticleListByThree(Integer pageNum, Integer pageSize, String categoryId, String title, String status, String username) {
        PageHelper.startPage(pageNum,pageSize);
        List<Article> articleList = articleMapper.getArticleListByThree(categoryId,title,status,username);
        return new PageInfo<>(articleList);
    }

    private String makeId() {
        return "AR"+System.currentTimeMillis();
    }

}
